package cn.gok.webSocket;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @Author: chen fan
 * @Date: 2022/3/17 20:03
 * @Description:
 *      WebSocket的客户端工具类， Servlet 可以借助该工具类中的 WebSocket的客户端
 *      去间接的调用WebSocket的服务端
 */
@ClientEndpoint
public class WebSocketClient {

    /**
     * WebSocket 客户端对象
     */
    private WebSocketContainer webSocketContainer;

    private Session session;
    public WebSocketClient(){
        webSocketContainer = ContainerProvider.getWebSocketContainer();

        //建立个WebSocket服务器的连接 , 获取发送信息的 session对象
        try {
            session = webSocketContainer.
                    connectToServer(this, new URI("ws://localhost:8080/webSocketServer"));
        } catch (DeploymentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(String message){
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
